﻿using Sidvall.Net;
using Sidvall.Net.Mime;
using Sidvall.UI.Wpf.Test.ViewModels;
using System.Threading.Tasks;
using System.Windows;

namespace Sidvall.UI.Wpf.Test
{
    public partial class MainWindow : Window
    {
        #region Public Members

        #region HttpClient

        private IHttpClient _HttpClient;
        public IHttpClient HttpClient
        {
            get
            {
                if (_HttpClient == null)
                {
                    var settings = new HttpClientSettings()
                    {
                        AllowAutoRedirect = false,
                    };
                    settings.ResponseTypes.Clear();
                    settings.ResponseTypes.Add(MediaType.TextHtml);
                    _HttpClient = Sidvall.SystemContext.Current.HttpClientFactory.GetHttpClient(settings);
                }
                return _HttpClient;
            }
            private set
            {
                _HttpClient = value;
            }
        }

        #endregion
        #region ViewModel

        public MainWindowViewModel ViewModel
        {
            get
            {
                return (MainWindowViewModel)this.DataContext;
            }
            set
            {
                this.DataContext = value;
            }
        }

        #endregion

        #endregion
        #region Private Members

        #region LogOnAsync

        private async Task LogOnAsync(bool logOff)
        {
            Sidvall.UI.SystemContext.Current.DialogManager.DialogIdentityProviders.Clear();
            Sidvall.UI.SystemContext.Current.DialogManager.DialogIdentityProviders.Add("PingFederate", "Volvo", new Sidvall.UI.Wpf.Dialogs.PingFederateIdentityProviderDialogManager());

            var root = @"https://apps.ivl.se/SecurityManager_OrderManager";
            var redirectAddress = @"https://apps.ivl.se/ordermanager/";
            var client = @"ordermanagerclient";

            var tokenResponse = await Sidvall.UI.SystemContext.Current.DialogManager.LogOnAsync(root + "/core/connect/authorize",
                client,
                "code id_token token",
                "openid profile email phone offline_access",
                redirectAddress,
                Sidvall.Security.TwoFactorProvider.None,
                null,
                root + "/core/connect/endsession",
                null,
                root + "/core/connect/token",
                "secret");

            if (tokenResponse?.TokenResponse != null)
                await Sidvall.UI.SystemContext.Current.DialogManager.ShowMessageAsync("OK", tokenResponse?.TokenResponse?.RefreshToken, UI.Dialogs.MessageType.Information);
        }

        #endregion
        #region LogonTestAsync

        private async Task LogonTestAsync()
        {
            HttpResponse response;
            System.Uri location;
            string startUrl, content, form;

            var root = @"https://apps.ivl.se/SecurityManager_OrderManager";
            var redirectAddress = @"https://apps.ivl.se/ordermanager/";
            var client = @"ordermanagerclient";
            var externalProvider = "PingFederate";

            // Call authorization server
            var authenticationClient = Sidvall.SystemContext.Current.AuthenticationManager.GetAuthenticationClient(root + "/core/connect/authorize");
            startUrl = authenticationClient.CreateAuthorizeAddress(client,
               "code id_token token",
               "openid profile email phone offline_access",
               redirectAddress,
               "state",
               "nonce",
               null,
               null,
               null,
               null,
               null,
               null,
               null);
            response = await this.HttpClient.GetAsync(startUrl);
            location = new System.Uri(startUrl);
            while (response.StatusCode == System.Net.HttpStatusCode.Found)
            {
                location = response.Headers.Location;
                response = await this.HttpClient.GetAsync(location, HttpCompletionOption.ResponseContentRead, System.Threading.CancellationToken.None);
            }

            // Call external authorization server
            content = await response.GetContentAsStringAsync();
            var pos1 = content.LastIndexOf("&quot;" + externalProvider + "&quot;");
            pos1 = content.IndexOf("&quot;href&quot;:&quot;", pos1);
            pos1 = pos1 + "&quot;href&quot;:&quot;".Length;
            var pos2 = content.IndexOf("&quot;", pos1 + 1);
            startUrl = content.Substring(pos1, pos2 - pos1).Replace("&amp;", "&");
            response = await this.HttpClient.GetAsync(startUrl);
            location = new System.Uri(startUrl);
            while (response.StatusCode == System.Net.HttpStatusCode.Found)
            {
                location = response.Headers.Location;
                response = await this.HttpClient.GetAsync(location, HttpCompletionOption.ResponseContentRead, System.Threading.CancellationToken.None);
            }

            // Post username & password to external authorization server
            content = await response.GetContentAsStringAsync();
            form = "pf.adapterId=" + System.Net.WebUtility.UrlEncode("FormWAMVang")
                + "&pf.ok=clicked&pf.username=" + System.Net.WebUtility.UrlEncode("anders") + "&pf.pass=" + System.Net.WebUtility.UrlEncode("password");
            response = await this.HttpClient.PostAsync(location, form, MediaType.ApplicationFormUrlEncoded, System.Threading.CancellationToken.None);
            content = await response.GetContentAsStringAsync();
        }

        #endregion

        #endregion
        #region Events

        private async void button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var busyManager = new Sidvall.Data.BusyManager(this.ViewModel))
                {
                    this.button.IsEnabled = false;
                    await LogOnAsync(true);
                }
            }
            catch (System.Exception ex)
            {
                await Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync(ex);
            }
            finally
            {
                this.button.IsEnabled = true;
            }
        }
        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                using (var busyManager = new Sidvall.Data.BusyManager(this.ViewModel))
                {
                    await LogOnAsync(false);
                }
            }
            catch (System.Exception ex)
            {
                await Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync(ex);
            }
        }

        #endregion
        #region Constructors

        public MainWindow()
        {
            InitializeComponent();

            this.Width = 1024;
            this.Height = 800;
            //this.WebControl.HtmlSource = "http://www.bing.com";

            this.Loaded += MainWindow_Loaded;
        }

        #endregion
    }
}
